package cn.afactory.tygz.db;

import android.content.Context;
import android.database.Cursor;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.common.DirConstants;
import cn.afactory.tygz.common.MsgType;
import cn.afactory.tygz.model.MessageDetail;
import cn.afactory.tygz.model.PrivateUserInfo;
import cn.afactory.tygz.model.SysMessageItem;
import cn.afactory.tygz.model.UserInfo;
import cn.afactory.tygz.ui.base.utils.HarwkinLogUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;

public class DBManager {
    public static final int VERSION = 1;
    public static DBManager mDBManager;
    private DbUtils mDbUtils ;
    private Context mContext;
    public DBManager(Context context){
        mContext = context;
        init();
    }

    private String getDBName(){
        String dbName = "tygz_" + SPUtils.getUid(mContext) + ".db";
        HarwkinLogUtils.getInstance().info(dbName);
        return dbName;
    }

    private void init(){
//        mDbUtils = DbUtils.create(mContext, DirConstants.DIR_DB, getDBName(), VERSION, new DbUtils.DbUpgradeListener(){
//
//            @Override
//            public void onUpgrade(DbUtils dbUtils, int i, int i1) {
//
//            }
//        });

        mDbUtils = DbUtils.create(mContext, getDBName(), VERSION, new DbUtils.DbUpgradeListener() {
            @Override
            public void onUpgrade(DbUtils dbUtils, int oldVersion, int newVersion) {

            }
        });
    }

    public static DBManager getInstance(Context context){
        if(mDBManager == null){
            mDBManager = new DBManager(context);
        }

        return mDBManager;
    }

    /**
     * 保存对象到数据库
     * @param obj
     */
    public void saveOrUpdate(Object obj){
        try {
            mDbUtils.saveOrUpdate(obj);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前用户登陆信息
     * @return
     */
    public UserInfo getDefaultUserInfo(){
        UserInfo userLoginInfo = null;
        try {
            userLoginInfo = mDbUtils.findFirst(UserInfo.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return userLoginInfo;
    }

    /**
     * 保存用户信息
     * @param userLoginInfo
     */
    public void saveUserInfo(UserInfo userLoginInfo){
        try {
            SPUtils.setNickName(mContext,userLoginInfo.nickName);
            SPUtils.setUserIcon(mContext,userLoginInfo.userIcon);
            mDbUtils.saveOrUpdate(userLoginInfo);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除用户登录信息
     */
    public void deleteUserInfo(){
        try {
            mDbUtils.dropTable(UserInfo.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    //******************************私信列表和系统消息 Start************************//
    /**
     * 更新Threads
     * @param threadsList
     */
    public synchronized void updateThreads(List<PrivateUserInfo> threadsList){
        if(threadsList == null || threadsList.size() == 0){
            return ;
        }
        try {
            mDbUtils.saveOrUpdateAll(threadsList);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有私信列表
     * @return
     */
    public synchronized List<PrivateUserInfo> getAllPrivateUsers(){
        try {
            List<PrivateUserInfo> users = mDbUtils.findAll(PrivateUserInfo.class);
            return users;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存消息
     * @param list
     */
    public synchronized void updateMessageList(List<MessageDetail> list){
        if(list == null || list.size() == 0){
            return ;
        }
        try {
            mDbUtils.saveOrUpdateAll(list);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取消息列表
     * @param userId
     * @param pageIndex
     * @param pageSize
     * @param addTime
     * @return
     */
    public synchronized List<MessageDetail> getMessageListByUserId(long userId,int pageIndex,int pageSize,long addTime){
        try {
//            String sql = String.format("select * from %s where '%s' = '%s' and '%s' <= '%s' Limit '%s' Offset '%s'",
//                    MessageDetail.TABLE_NAME,
//                    MessageDetail.USER_ID,
//                    userId,
//                    MessageDetail.CREATE_DATE,
//                    addTime,
//                    pageSize,
//                    pageIndex * pageSize);
//            Cursor cursor = mDbUtils.execQuery(sql);

            Selector selector = Selector.from(MessageDetail.class);
            selector.where(WhereBuilder.b());
            selector.and(MessageDetail.USER_ID, "=", userId);
            selector.and(MessageDetail.CREATE_DATE, "<=", addTime);
            selector.limit(pageSize);
            selector.orderBy(MessageDetail.CREATE_DATE, true);
            selector.offset(pageIndex * pageSize);
            List<MessageDetail> list = mDbUtils.findAll(selector);
            return  list== null?new ArrayList<MessageDetail>():list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<MessageDetail>();
    }


    /**
     * 存储系统消息
     * @param list
     */
    public synchronized void updateSysMessageList(List<SysMessageItem> list){
        if(list == null || list.size() == 0){
            return ;
        }
        try {
            mDbUtils.saveOrUpdateAll(list);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取系统消息列表
     * @param pageIndex
     * @param pageSize
     * @param addTime
     * @return
     */
    public synchronized List<SysMessageItem> getSysMessageList(int pageIndex,int pageSize,long addTime){
        try {
            Selector selector = Selector.from(SysMessageItem.class);
            selector.where(WhereBuilder.b());
            selector.and(MessageDetail.CREATE_DATE, "<=", addTime);
            selector.limit(pageSize);
            selector.orderBy(MessageDetail.CREATE_DATE,true);
            selector.offset(pageIndex * pageSize);
            return mDbUtils.findAll(selector);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //插入一条新的消息
    public synchronized MessageDetail insertNewMessage(String msg,long targetUserId,String targetNickName,String targetUserIcon){
        MessageDetail messageDetail = new MessageDetail();
        messageDetail.type = MsgType.SEND;
        messageDetail.msg = msg;
        messageDetail.addTime = System.currentTimeMillis();
        messageDetail.nickName = SPUtils.getNickName(mContext);
        messageDetail.userId = SPUtils.getUid(mContext);
        messageDetail.userIcon = SPUtils.getUserIcon(mContext);
        try {
            mDbUtils.saveOrUpdate(messageDetail);
            updateThreads(messageDetail,targetUserId,targetNickName,targetUserIcon);
            return messageDetail;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }

    public synchronized void updateThreads(MessageDetail messageDetail,
                                           long targetUserId,
                                           String targetNickName,
                                           String targetUserIcon){
        Threads threads = new Threads();
        threads.nickName = targetNickName;
        threads.updateDate = messageDetail.addTime;
        threads.update_content= messageDetail.msg;
        threads.userIcon = targetUserIcon;
        threads.userId = targetUserId;

        try {
            mDbUtils.saveOrUpdate(threads);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    //******************************私信列表和系统消息 End************************//
}
